﻿using LayIM.AspNetCore.Core.Models.Base;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace LayIM.AspNetCore.Storage.Infra.Dapper.Repository
{
    public class GroupMemberRepository : BaseRepository
    {
        public GroupMemberRepository(DBConnectionConfig dbConfig) : base(dbConfig)
        { }


        protected override string TableName => "layim_group_member";

        public Task<IEnumerable<long>> GetUserBigGroups(string userId)
        {
            var sql = "SELECT [group_id] FROM layim_group_member where member_id=@uid";
            return QueryAsync<long>(sql, new { uid = userId });
        }

        public Task<IEnumerable<long>> GetUsersByGroupId(string groupId)
        {
            var sql = "SELECT member_id  FROM layim_group_member where group_id=@groupid";
            return QueryAsync<long>(sql, new { groupid = groupId });
        }

        public Task<IEnumerable<UserModel>> GetMembersNotFriend(string userId,string searchKey)
        {
            var sql = "SELECT lu.UserId as [id],lu.[name] as username,lu.Avator as [avatar],lu.Signature as [sign] FROM SystemUser lu where lu.UserId!=@uid and not exists(select 1 from layim_friend_relation where (uid1=@uid and uid2=lu.UserId) or (uid1=lu.UserId and uid2=@uid))";
            if (!string.IsNullOrEmpty(searchKey))
            {
                sql += " and lu.Name like '%" + searchKey + "%'";
            }
            return QueryAsync<UserModel>(sql, new { uid = userId });
        }

        public Task<IEnumerable<GroupModel>> GetGroupsNotJoin(string userId)
        {
            var sql = "SELECT lbg.*,lbg.name groupname,lu.userid,lu.name username,(select count(1) from layim_group_member where group_id=lbg.id) userCount FROM layim_big_group lbg inner join SystemUser lu on lbg.create_by=lu.UserId where not exists(select 1 from layim_group_member where member_id=@uid and group_id=lbg.id)";
            return QueryAsync<GroupModel>(sql, new { uid = userId });
        }
    }
}
